<template>
  <n-modal v-model:show="showModal" class="pay-dialog-box">
    <n-card
        title=" "
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
        style="width: 680px; position: fixed; top: 230px;left:0;right:0;margin: 0 auto;height: 520px;"
    >
      <template #header-extra>
        <a href="javascript:void(0);" class="close-pay" @click="handleClose">
          <svg t="1701626146394" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
               p-id="4224" width="20" height="20">
            <path
                d="M571.733333 512l268.8-268.8c17.066667-17.066667 17.066667-42.666667 0-59.733333-17.066667-17.066667-42.666667-17.066667-59.733333 0L512 452.266667 243.2 183.466667c-17.066667-17.066667-42.666667-17.066667-59.733333 0-17.066667 17.066667-17.066667 42.666667 0 59.733333L452.266667 512 183.466667 780.8c-17.066667 17.066667-17.066667 42.666667 0 59.733333 8.533333 8.533333 19.2 12.8 29.866666 12.8s21.333333-4.266667 29.866667-12.8L512 571.733333l268.8 268.8c8.533333 8.533333 19.2 12.8 29.866667 12.8s21.333333-4.266667 29.866666-12.8c17.066667-17.066667 17.066667-42.666667 0-59.733333L571.733333 512z"
                fill="#666666" p-id="4225"></path>
          </svg>
        </a>
      </template>

      <client-only>
        <n-tabs default-value="weixin" justify-content="space-evenly" type="line" :on-update:value="handleChangeTab">
          <n-tab-pane name="weixin" tab="微信">
            <div class="flex justify-center flex-col items-center mt-5 pb-5">
              <img :src="payCodeUrl" width="240" height="240"/>
              <div class="mt--3 fw red">支付金额：￥{{ currentPrice }}元</div>
              <div class="mt--3">支付时间还剩：{{ payCount }}s</div>
            </div>
          </n-tab-pane>
          <n-tab-pane name="alipay" tab="支付宝">
            <div class="flex justify-center flex-col items-center mt-5 pb-5">
              <img :src="payCodeUrl" width="240" height="240"/>
              <div class="mt--3 fw red">支付金额：￥{{ currentPrice }}元</div>
              <div class="mt--3">支付的时间：{{ payCount }}s</div>
            </div>
          </n-tab-pane>
          <n-tab-pane name="code" tab="兑换码">
            <div class="flex justify-center  items-center mt-20" style="padding: 10px 40px 40px;">
              <input v-model="code" placeholder="请输入20位兑换码" maxlength="20" min="20" max="20"/>
              <n-button class="ml-2" @click="handleDuiHuanCode" type="success">兑换</n-button>
            </div>
          </n-tab-pane>
          <n-tab-pane name="coin" tab="学习币兑换">
            <div class="flex justify-center flex-c items-center mt-5" style="padding: 40px 40px 40px;">
              <h1 class="fz18 green">用户：【{{userInfo.nickname}}】您好！</h1>
              <h3 class="mt15 fz16">你当前学习币是：【{{userInfo.coin}} 】个</h3>
              <p class="mt15 fz16 fb">当前课程所需学习币是：{{currentPrice}}个</p>
              <div v-if="currentPrice*1 > userInfo.coin" class="red mt5">友情提示：学习币不足！</div>
              <nuxt-link class="mt10"  to="/user/wallet" target="_blank" v-if="currentPrice*1 > userInfo.coin"><n-button size="large"  class="ml-2" @click="handleDuiHuanCode" type="success"><i class="iconfont icon-fabu mr5"></i>点击前往充币</n-button></nuxt-link>
              <n-button  v-else class="ml-2 mt10" size="large" @click="handleDuiHuanCoin" type="primary"><i class="iconfont icon-fabu mr5"></i>点击兑换</n-button>
            </div>
          </n-tab-pane>
        </n-tabs>
      </client-only>
    </n-card>
  </n-modal>
</template>

<script setup>
// 二维码生成器
import QRCode from 'qrcode'
// 控制支付弹窗的关闭和打开
const showModal = ref(false)
// 获取支付数据
const payData = ref({})
// 默认图的设置，防止出现裂图
const payCodeUrl = ref("/imgs/1px.png")
// 支付当前的课程
const currentSpecialId = ref("")
const currentBindId = ref("")
const currentPrice = ref(0)
const userInfo = ref({})
// 支付的时长，单位是秒
const payTotalTimer = 300
const payCount = ref(payTotalTimer)
const payMethod = ref("weixin")
// 支付轮询定时器
let payTimer = null
// 支付时间计数的定时器
let payCountTimer = null
// 兑换码
const code = ref("")
// 模块
const props = defineProps({
  mode: {
    type: String,
    default: "specialbind"
  }
})


// 打开支付窗口
const handleOpen = (specialId,bindId, price) => {
  showModal.value = true
  if (payTimer) clearInterval(payTimer);
  if (payCountTimer) clearInterval(payCountTimer);
  payCount.value = payTotalTimer
  currentSpecialId.value = specialId
  currentBindId.value = bindId
  currentPrice.value = price
  handleCreateNativeWeixin()
}

// 生成课程的支付二维码
const handleCreateNativeWeixin = async () => {
  try {
    payMethod.value = "weixin"
    // 根据课程id获取下单的微信支付地址
    const resp = await useCreateNativeSpecialBindApi(currentBindId.value,currentSpecialId.value, payMethod.value, props.mode)
    // 获取服务端支付信息包括：微信支付地址，业务订单编号和状态success
    payData.value = resp.data
    // 生成二维码
    const qrCodeResp = await QRCode.toDataURL(resp.data.url, {
      width: 220,
      height: 240,
      margin: 2
    })
    // 把生成好的二维码的二进制的字符串赋值给状态数据管理payCodeUrl
    payCodeUrl.value = qrCodeResp
    // 保证每次都是从180开始
    payCount.value = payTotalTimer
    // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
    if (payTimer) clearInterval(payTimer)
    if (payCountTimer) clearInterval(payCountTimer)
    // 开始查询, 这里立即执行一次，去查询用户是否支付和购买此课程
    handleListenerPaySuccess()
    payTimer = setInterval(handleListenerPaySuccess, 3000)
    // 时间计数倒计时
    payCountTimer = setInterval(handleListenerTime, 1000)
  } catch (e) {
    if (payTimer) clearInterval(payTimer)
    if (payCountTimer) clearInterval(payCountTimer)
    payCodeUrl.value = ""
    payCount.value = 0
    useMessage().error(e.message)
  }
}

// 生成课程的支付二维码
const handleCreateNativeAlipay = async () => {
  try {
    payMethod.value = "alipay"
    // 根据课程id获取下单的微信支付地址
    const resp = await useCreateNativeSpecialBindApi(currentBindId.value,currentSpecialId.value, payMethod.value, props.mode)
    // 获取服务端支付信息包括：微信支付地址，业务订单编号和状态success
    payData.value = resp.data
    // 生成二维码
    const qrCodeResp = await QRCode.toDataURL(resp.data.url, {
      width: 220,
      height: 240,
      margin: 2
    })
    // 把生成好的二维码的二进制的字符串赋值给状态数据管理payCodeUrl
    payCodeUrl.value = qrCodeResp
    // 保证每次都是从180开始
    payCount.value = payTotalTimer
    // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
    if (payTimer) clearInterval(payTimer)
    if (payCountTimer) clearInterval(payCountTimer)
    // 开始查询, 这里立即执行一次，去查询用户是否支付和购买此课程
    handleListenerPaySuccess()
    payTimer = setInterval(handleListenerPaySuccess, 3000)
    // 时间计数倒计时
    payCountTimer = setInterval(handleListenerTime, 1000)
  } catch (e) {
    if (payTimer) clearInterval(payTimer)
    if (payCountTimer) clearInterval(payCountTimer)
    payCodeUrl.value = ""
    payCount.value = 0
    useMessage().error(e.message)
  }
}

// 支付查单
const handleListenerPaySuccess = async () => {
  try {
    await useFindNativeByTradeNoSpecialBindApi(payData.value.tradeNo, currentBindId.value,currentSpecialId.value, payMethod.value, props.mode)
    useMessage().success("支付成功,可以去个人中心查看订单信息!")
    if (payTimer) clearInterval(payTimer);
    if (payCountTimer) clearInterval(payCountTimer);
    payCount.value = payTotalTimer
    setTimeout(()=>{
      // 关闭定时器
      window.location.reload()
    },600)
  } catch (e) {
    if (e.code == 902) {
      useMessage().error(e.message)
      handleClose()
    }
  }
}

// 时间计数器
const handleListenerTime = () => {
  payCount.value--
  if (payCount.value == 0) {
    // 关闭支付
    handleClose()
  }
}

// 关闭支付窗口
const handleClose = () => {
  showModal.value = false
  // 生成和创建课程的微信支付二维码
  if (payTimer) clearInterval(payTimer);
  if (payCountTimer) clearInterval(payCountTimer);
  payCount.value = payTotalTimer
  currentPrice.value = 0
  currentSpecialId.value = ""
  currentBindId.value = ""
}

// 兑换课程
const handleDuiHuanCode = debounce(async () => {
  if (!code.value) {
    useMessage().error("请输入兑换码!")
    return
  }
  try {
    await useDuhuanSpecialBindApi(code.value, currentSpecialId.value,currentBindId.value)
    useMessage().success("兑换成功")
    setTimeout(()=>{
      // 关闭定时器
      window.location.reload()
    },600)
  } catch (e) {
    useMessage().error(e.message)
  }
}, 600)

// 金币兑换课程
const handleDuiHuanCoin = debounce(async () => {
  try {
    await useDuhuanCoinSpecialBindApi(currentSpecialId.value, currentBindId.value)
    useMessage().success("兑换成功")
    setTimeout(()=>{
      // 关闭定时器
      window.location.reload()
    },600)
  } catch (e) {
    useMessage().error(e.message)
  }
}, 600)

// 选项卡改变
const handleChangeTab = async (value) => {
  if (value == "code") {
    // 保证每次都是从180开始
    payCount.value = payTotalTimer
    // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
    if (payTimer) clearInterval(payTimer)
    if (payCountTimer) clearInterval(payCountTimer)
    payMethod.value = "code"
  } else if (value == "weixin") {
    payMethod.value = "weixin"
    handleCreateNativeWeixin()
  } else if (value == "alipay") {
    payMethod.value = "alipay"
    handleCreateNativeAlipay()
  } else if (value == "coin") {
    payCount.value = payTotalTimer
    // 这两行代码是把原来开启的定时器关闭，保证每次支付都是最新的状态，（清楚旧的定时器，保证每次都是最新状态）
    if (payTimer) clearInterval(payTimer)
    if (payCountTimer) clearInterval(payCountTimer)
    payMethod.value = "coin"
    const resp = await useLoadUserGetApi()
    userInfo.value = resp.data
  }
}

// 暴露方法
defineExpose({handleOpen})
</script>
<style scoped>
.pay-dialog-box {
  position: relative;
}

.pay-dialog-box .close-pay {
  display: none;
  position: absolute;
  top: 25px;
  right: 25px;
}

.pay-dialog-box:hover .close-pay {
  display: block
}
</style>